<script setup lang='ts' name="one-policy-table">
import type { VxeGridProps, VxePagerEvents } from "vxe-table"
import { cloneDeep } from 'lodash-es'
import { downloadFile } from '@fl/utils/fn'
import { SearchForm } from '@fl/components'
import { getApplyStatisticsAll, getAreaList } from '@fl/api/anjutong'

const initialState = {
    applyTime: [],
    policyLevel: undefined,
    areaCode: '00',
    areaCodeList: []
}
const areaList = ref([])
const updateKey = ref(666)
const state = ref(cloneDeep(initialState))
const columns = ref([
    {
        fieldProps: {
            'endPlaceholder': '申请时间起',
            'startPlaceholder': '申请时间止',
            'type': 'daterange',
            'value-format': 'YYYY-MM-DD',
        },
        label: '申请时间',
        prop: 'applyTime',
        valueType: 'date-picker',
    },
    {
        label: '政策层级',
        options: [
            {
                label: '市级',
                value: 2,
            },
            {
                label: '区级',
                value: 3,
            },
        ],
        prop: 'policyLevel',
        valueType: 'select',
    },
    {
        label: '市',
        options: [
            {
                label: '武汉市',
                value: '00',
            }
        ],
        prop: 'areaCode',
        valueType: 'select',
    },
    {
        fieldProps: {
            'multiple': true,
        },
        label: '区划',
        options: areaList,
        prop: 'areaCodeList',
        valueType: 'select',
    },
    {
        label: '发布时间',
        options: [{
            label: '2024',
            value: '2024'
        }, {
            label: '2025',
            value: '2025'
        }],
        prop: 'publishTime',
        valueType: 'select',
    },
])
const loading = ref(false)
const gridOptions = reactive<VxeGridProps>({
    border: true,
    stripe: false,
    mergeCells: [],
    columns: [
        // { type: 'seq', width: 70 ,title: '序号'},
        { field: 'publishTime', title: '发布时间', showOverflow: true },
        { field: 'policyLevel', title: '政策层级',slots: { default: 'policyLevel' }, showOverflow: true },
        { field: 'city', title: '市', showOverflow: true },
        { field: 'district', title: '县/区划', showOverflow: true },
        { field: 'subsidyType', title: '补贴类型', showOverflow: true },
        { field: 'audit', title: '待审核', showOverflow: true },
        { field: 'checked', title: '审核通过', showOverflow: true },
        { field: 'refuse', title: '审核不通过', showOverflow: true },
        { field: 'grantCount', title: '已发放', showOverflow: true },
        { field: 'cancel', title: '已作废', showOverflow: true },
        { field: 'total', title: '小计', showOverflow: true },
        { field: 'qhnj', title: '合计', showOverflow: true },
    ],
    data: []
});
const publishTimeArr = ref([])
const policyArr = ref([])
const districtArr = ref([])
const downladingUrl = import.meta.env?.DEV ? '/fl/goodhouse/house/policy/apply/applyStatisticsAllExport' : '/goodhouse/house/policy/apply/applyStatisticsAllExport'

init()
/**
 * methods start
 */

 function init() {
    getCurrentAreaList()
    getDataList()
 }
 function getCurrentAreaList() {
    getAreaList().then(res=>{
        const { code, data } = res
        if(code === 200) {
            areaList.value = data.map(item=>({
                ...item,
                label: item.areaName,
                value: item.areaCode
            }))

        }
    })
 }

function getDataList() {
    publishTimeArr.value = []
    gridOptions.mergeCells = []
    districtArr.value = []
    policyArr.value = []
    loading.value = true
    getApplyStatisticsAll({
        ...state.value,
        applyStartTime: state.value?.applyTime?.[0],
        applyEndTime: state.value?.applyTime?.[1],
        applyTime: undefined

    }).then(async (res)=>{
        const { code, data } = res
        if(code !== 200) {
            return
        } 
        const areaCodeSubtotals = {};
        const subsidyTypeCodeData = {};
        data.map((item, index) => {
            item.$index = index
            console.log(232323,data[index + 1])
            if(data[index + 1] && data[index].publishTime !== data[index + 1].publishTime) {
                publishTimeArr.value.push(index)
            }
            if(item.policyLevel === 2) {
                policyArr.value.push(index)
               
            }
            if(item.policyLevel === 3) {
                districtArr.value.push({index, district:item.district})
                if (!areaCodeSubtotals[item.areaCode]) {
                    areaCodeSubtotals[item.areaCode] = 0;
                }
            }
            return item
        })
        console.log(9000,publishTimeArr.value)
        if(publishTimeArr.value.length) {
            // gridOptions.mergeCells?.push({
            //         row: 0,
            //         col: 0,
            //         rowspan: publishTimeArr.value[0] + 1, 
            //         colspan: 1
            //     },{
            //         row: 3,
            //         col: 0,
            //         rowspan: 13, 
            //         colspan: 1
            //     },{
            //         row: 16,
            //         col: 0,
            //         rowspan: 32, 
            //         colspan: 1
            //     })
            publishTimeArr.value.forEach((val, index) => {
                gridOptions.mergeCells?.push({
                    row: index > 0 ? publishTimeArr.value[index -1] + 1 : 0,
                    col: 0,
                    rowspan:  index === 0 ? val + 1 : val - publishTimeArr.value[index -1], 
                    colspan: 1
                })
            })

        }
        if(policyArr.value.length) {
            gridOptions.mergeCells?.push({
                row: policyArr.value[0],
                col: 1,
                rowspan: policyArr.value.length, 
                colspan: 1
            },{
                row: policyArr.value[0],
                col: 2, 
                rowspan: policyArr.value.length, 
                colspan: 1
            })
        }
        if(districtArr.value.length) {
            gridOptions.mergeCells?.push({
                row: districtArr.value[0].index,
                col: 0, 
                rowspan: districtArr.value.length, 
                colspan: 1
            },{
                row: districtArr.value[0].index,
                col: 1, 
                rowspan: districtArr.value.length, 
                colspan: 1
            },{
                row: districtArr.value[0].index,
                col: 2, 
                rowspan: districtArr.value.length, 
                colspan: 1
            })
        }
        const groupedData = {};
        data.forEach(item => {
            if(item.policyLevel === 2) {
                if (!subsidyTypeCodeData[item.subsidyTypeCode]) {
                    subsidyTypeCodeData[item.subsidyTypeCode] = [];
                }
                subsidyTypeCodeData[item.subsidyTypeCode].push(item)
            }
            if (item.policyLevel === 3) {
                if (!groupedData[item.areaCode]) {
                    groupedData[item.areaCode] = [];
                }
                groupedData[item.areaCode].push(item);
            }
        });
        const subsidyTypeCodeArr = Object.values(subsidyTypeCodeData)
        subsidyTypeCodeArr.forEach((item) => {
            gridOptions.mergeCells?.push({
                row: item[0].$index,
                col: 11, 
                rowspan: item.length, 
                colspan: 1
            })
        })
        const multiDimensionalArray = Object.values(groupedData)
        await getMergeCellData('city',subsidyTypeCodeArr,data)
        await getMergeCellData('district',multiDimensionalArray,data)
        gridOptions.data = data
        updateKey.value = +new Date()
        loading.value = false
    })
 }
 function getMergeCellData(type,list,data) {
    list.forEach((item) => {
            if(type === 'district') {
                gridOptions.mergeCells?.push({
                    row: item[0].$index,
                    col: 3,
                    rowspan: item.length,
                    colspan: 1
                },{
                    row: item[0].$index,
                    col: 11,
                    rowspan: item.length,
                    colspan: 1
                })

            }else {
                gridOptions.mergeCells?.push({
                    row: item[0].$index,
                    col: 4,
                    rowspan: item.length,
                    colspan: 1
                })
            }
        })
 }
 

 function resetSearch() {
    state.value = cloneDeep(initialState)
    getDataList()
 }

 function submitSearch(values) {
   if(values) {
        state.value = values
        getDataList()
   }
 }
 

/**
 * methods end
 */

</script>
<template>
    <div class="on-policy-table">
        <ElCard class="mb-20"
                shadow="never"
        >
            <SearchForm v-model="state"
                        :columns="columns"
                        submit-text="搜索"
                        @reset="resetSearch"
                        @submit="submitSearch"
            >
            </SearchForm>
        </ElCard>
        <el-button type="primary" @click="downloadFile(downladingUrl, 'POST', { 'Content-Type': 'application/json' }, {
                                   ...state,
                                   applyStartTime: state?.applyTime?.[0],
                                   applyEndTime: state?.applyTime?.[1],
                                   applyTime: undefined
                               }, `role_${new Date().getTime()}.xlsx`)">导出</el-button>
        <ElCard class="mt-20"
                shadow="never"
        >
            <vxe-grid v-bind="gridOptions" v-loading="loading" :key="updateKey">
                <template #policyLevel="{ row }">
                {{  ['','全部','市','区'][row.policyLevel] }}
                </template>
            </vxe-grid>
        </ElCard>
    </div>
</template>
<style lang="scss" scoped>

</style>